package com.lsh.airticket.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyuncs.exceptions.ClientException;
import com.lsh.airticket.dto.Result;
import com.lsh.airticket.exception.UserException;
import com.lsh.airticket.service.impl.SendSms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author lsh
 * @date 2021/2/28
 **/
@RestController
@RequestMapping("sms")
public class SMSController {

    @Autowired
    SendSms sendSms;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 发送短信
     * @param phone
     * @return
     */
    @GetMapping("/sendSMS")
    public Result sendSMS(String phone) {
        if (StrUtil.isEmpty(phone)) {
            throw new UserException("发送失败");
        }
        // 生成验证码
        int[] codes = RandomUtil.randomInts(6);
        String code = ""+codes[0]+codes[1]+codes[2]+codes[3]+codes[4]+codes[5];
        System.out.println(code);
        try {
            sendSms.sendMessage(code, phone);
        } catch (Exception e) {
            e.printStackTrace();
            throw new UserException("发送失败");
        }
        redisTemplate.opsForValue().set(phone, code);
        //设置token的有效时间
        redisTemplate.expire(phone,5, TimeUnit.MINUTES);

        return Result.result().setMsg("发送成功");
    }
}
